<template>
	<div class="comment">
		<m-header ref="header" class="header">
      <div slot="middle" class="tab">
        <span>评论({{ total }})</span>
      </div>
      <div slot="left" @click="$router.go(-1)">
        <i class="iconfont icon-xiangzuo" />
      </div>
		</m-header>
		<div class="tabs" ref="tab" :style="tabsStyle">
			<div class="left">
				<span>评论区</span>
			</div>
			<div class="right" ref="tabs">
				<div v-for="(tab, index) of tabs"
							:key="tab"
							:class="index === active ? 'active' : ''"
							@click="clickTab(index)"
				><span>{{ tab }}</span></div>
			</div>
		</div>

		<div class="warpper">
			<div class="inner">
				<scroll :data='list'
								:bounce='false'
								listen-scroll
								pullUpLoad
								@scroll='scroll'
								@pullingUp='pullingUp'>
					<div class="top-warpper" ref="topWarpper">
						<div class="info" v-if="info">
							<card :image='info.image'
										:title="info.title"
										:subTitle="info.subTitle"
										:imageWidth='70'
										:imageHeight='70'
										direction='row'
							/>
						</div>
					</div>
					<ul class="comment-list" ref="list" @click="replyToComment">
						<li class="item" v-for="(item, index) of list" :key="index" :data-commentId='item.commentId' :data-nickname='item.user.nickname' v-ripple>
							<div class="avatar" v-if="item.user">
								<img v-lazy='item.user.avatarUrl' />
							</div>
							<div class="comment-contnet border-1px-bottom">
								<div class="top">
									<div class="user">
										<span class="nickname">
											{{ item.user.nickname }}
											<van-tag v-if="item.user.userId === userId" round size="mini" type="danger" plain class="author">作者</van-tag>
										</span>
										<span class="time">
											{{ item.time | formatTime }}
											<span v-if="item.isHot && active === 0">‧ 精彩评论</span>
										</span>
									</div>
									<div class="like" :class="item.liked ? 'isLike': ''" @click.stop="like(item, index)">
										<span v-if="item.likedCount">{{ item.likedCount }}</span>
										<i class="iconfont" :class="item.liked ? 'icon-zan1' : 'icon-zan'"/>
									</div>
								</div>
								<div class="content" v-html="emojiFormat(item.content)"></div>
								<span class="reply" v-if="replyList[item.commentId]">{{ replyList[item.commentId].length }}条回复 ></span>
							</div>
						</li>
					</ul>
				</scroll>
			</div>
		</div>
		<input-box ref="inputBox" @send='send' />
	</div>
</template>
<script>
import { playlist, music, album, like, comment } from 'api/comment'
import Scroll from 'base/scroll'
import MHeader from 'base/m-header'
import Card from 'base/card'
import { emojiFormat } from '@/utils/emoji'
import InputBox from 'base/input-box'

export default {
	components: {
		Scroll,
		MHeader,
		Card,
		InputBox
	},
	data() {
		return {
			active: 0,
			tabs: ['推荐', '最热', '最新'],
			translateY: 0,
			total: 0,
			info: null,
			pagination: {
				limit: 20,
				offset: 0
			},
			comments: [],
			hotComments: [],
			list: [],
			commentTxt: '',
			commentId: null,
			replyList: {},
		}
	},
	mounted() {
		this.init()
	},
	computed: {
		tabsStyle() {
			return {
				transform: `translate3d(0, ${this.translateY}px, 0)`
			}
		},
		topWarpperHeight() {
			return this.$refs.topWarpper.offsetHeight
		},
		tabHeight() {
			return this.$refs.tab.offsetHeight
		},
		headerHeight() {
			return this.$refs.header.$el.offsetHeight
		}
	},
	methods: {
		init() {
			const { type, id, info } = this.$route.params // 0: 歌曲 2: 歌单 3: 专辑

			if (!type || !id) {
				this.$router.push('/discovery')
				return
			}

			this.id = id
			this.type = type
			this.func = type === '0' ? music :
									type === '2' ? playlist : album
			this.info = this.formatInfo(info)

			this.getList(type)

			this.$nextTick(() => {
				this.$refs.tab.style['top'] = `${this.topWarpperHeight + this.headerHeight}px`
				this.$refs.topWarpper.style['padding-top'] = `${this.headerHeight}px`
				this.$refs.list.style['padding-top'] = `${this.tabHeight}px`
			})
		},
		formatInfo(info) {
			let _info = {
				image: info.picUrl,
				title: info.name,				
			}
			_info.subTitle = this.type === '0' ? info.artistsNames : 
											this.type === '2' ? `by ${info.creator.nickname}` : `${info.artist.name}`
			return _info
		},
		clickTab(index) {
			this.active = index
			this.pagination.offset = 0
			this.list = []
			this.getList()
			this.$refs.inputBox.clear()
			this.replyList = {}
		},
		getList() {
			return this.func(this.id, this.pagination.limit, this.pagination.offset).then(res => {
				this.userId = res.userId // 创建人ID
				this.comments = this.normalizeList(res.comments || [])
				this.hotComments = res.hotComments || []
				this.hotComments.forEach(item => item.isHot = true)
				this.more = res.more
				this.total = res.total
				this.setList()
			})
		},
		setList() {
			let list = []
			switch (this.active) {
				case 0: // 推荐
					if (this.hotComments.length) {
						list = this.hotComments.splice(0, 5)	
					}
					list = list.concat(this.comments)
					break;
				case 1: // 最热
					list = this.hotComments.concat(this.comments)
					break;
				case 2: // 最新
					list = this.comments
					break;
			}
			this.list.push(...list)
		},
		normalizeList(list) {
			list.forEach(item => {
				const beReplied =item.beReplied[0]
				if (beReplied) {
					const { beRepliedCommentId } = beReplied
					if (this.replyList[beRepliedCommentId]) {
						this.replyList[beRepliedCommentId].push(beRepliedCommentId)
					} else {
						this.replyList[beRepliedCommentId] = [beRepliedCommentId]
					}
				}
			})
			return list.filter(item => !item.beReplied.length)
		},
		scroll({ y }) {
			this.translateY = Math.max(y, -this.topWarpperHeight)
		},
		pullingUp(finish) {
			if (this.more) {
				this.pagination.offset++
				this.getList().finally(() => finish())
			} else {
				finish()
			}
		},
		like({ liked, commentId }, index) {
			like(this.id, commentId, liked ? '0' : '1', this.type).then(() => {
				let item = this.list[index]
				item.liked = !liked
				liked ? item.likedCount-- : item.likedCount++
			})
		},
		replyToComment(e) {
			const { path } = e
			let node = path.find(item => item.nodeName === 'LI' && item.className === 'item')
			if (node) {
				if (!this.commentId) {
					this.commentId = node.getAttribute('data-commentId')
					this.$refs.inputBox.setPlaceholder(`回复${node.getAttribute('data-nickname')}:`)
				} else {
					this.$refs.inputBox.clear()
					this.commentId = null
				}
			}
		},
		send(txt) {
			let params = {
				id: this.id,
				t: '1',
				type: this.type,
				content: txt
			}

			if (this.commentId) {
				params.commentId = this.commentId
				params.t = '2'
			}

			comment(params).then(() => {
				this.$refs.inputBox.clear()
				this.$toast('发表成功')
				this.pagination.offset = 0
				this.list = []
				this.getList()
			})
		},
		emojiFormat(content) {
			return emojiFormat(content).replace(/\n/g, "<br/>")
		}
	},
	filters: {
		formatTime(timestamp) {
			let time = new Date(timestamp)
			let now = new Date()

			if (time.getFullYear() < now.getFullYear()) {
				return time.format('yyyy年MM月dd日')
			}

			if (time.getDate() < now.getDate()) {
				return time = time.format('MM月dd日')
			}

			let nowTime = now.getTime()
			let ftime = time.getTime()
			if ((nowTime - 3600000) < ftime) {
				return Math.round((nowTime - ftime) / 60000) + '分钟前'
			} else {
				return time.format('hh:mm')
			}
		}
	}
}
</script>
<style lang="less" scoped>
@import '~@/style/variable.less';
@import '~@/style/mixins.less';

.comment{
  position:fixed;
  top: 0;
  bottom: 0;
  background-color: white;
	width: 100%;
	z-index: 5;
	.warpper{
		position: fixed;
		top: 0;
		bottom: 40px;
		width: 100%;
		.inner{
			padding: 0 10px;
			height: 100%;
		}
	}
	.tabs{
		height: 30px;
		line-height: 30px;
		display: flex;
		position: absolute;
		width: 100%;
		background-color: white;
		z-index: 1;
		>div{
			flex: 1;
		}
		.left{
			font-size: @font-size-normal;
			padding-left: 10px;
		}
		.right{
			display: flex;
			padding-right: 10px;
			>div{
				flex: 1;
				text-align: right;
				color: @text-color-light;
			}
			.active{
				font-weight: bold;
				color: @text-color;
			}
		}
	}
	.header{
		position: absolute;
		width: 100%;
		background: white;
		z-index: 1;
	}
	.top-warpper{
		height: 80px;
	}
	.comment-list{
		.item{
			display: flex;
			.avatar{
				width: 40px;
				padding: 7px 0;
				img{
					width: 30px;
					height: 30px;
					border-radius: 100%;
				}
			}
			.comment-contnet{
				position: relative;
				display: flex;
				flex-direction: column;
				width: 100%;
				padding: 7px;
				box-sizing: border-box;
				.top{
					display: flex;
					height: 40px;
					width: 100%;
					.user{
						display: flex;
						flex-direction: column;
						flex: 1;
						.nickname{
							height: 50%;
							font-size: @font-size-small;
							.author{
								font-size: 8px;
							}
							img{
								width: 30px;
								height: 20px;
							}
							.ellipsis()
						}
						.time{
							height: 50%;
							color: @text-color-light;
							font-size: @font-size-mini;
						}
					}
					.like{
						font-size: @font-size-small;
						text-align: right;
						width: 60px;
						white-space: nowrap;
						>i{
							font-size: 1.2em;
						}
					}
					.isLike{
						color: red;
					}
				}
				.content{
					line-height: 1.5;
				}
				.reply{
					margin-top: 5px;
					color: #2799fd;
				}
			}
		}
	}
}
</style>